<?php
namespace App\Admin\Controllers\Operation;

use App\Admin\Actions\Operation\CalculateProfitTry;
use App\Admin\Ajax\Operation\ProfitAjax;
use App\Exporter\Operation\ProfitTryExporter;
use App\Models\Basics\AmazonCountry;
use App\Models\Basics\ExchangeRate;
use App\Models\Operation\ProfitSku;
use Encore\Admin\Admin;
use Encore\Admin\Layout\Content;
use App\Models\Basics\Transport;
use App\Models\Operation\ProfitTry;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;
class ProfitTryController extends AdminController{

    protected $title = '试算产品利润率';

    protected function grid()
    {
        Admin::script($this->_script());
        $grid = new Grid(new ProfitTry());
        $grid->model()->orderBy('id', 'DESC');
        $grid->model()->collection(function (Collection $collection){
            foreach($collection as $item) {
                $item->inventory_fee = round($item->sale_price * ProfitSku::$_inventory / 100 ,3);
                $item->other_fee = round($item->sale_price * ProfitSku::$_other / 100 ,3);
            }
            return $collection;
        });
        $grid->column('id','ID');
        $grid->column('country.country','国家');
        $grid->column('seller_id','销售员')->display(function ($value){
            return User::getUsernameById($value);
        });
        $grid->column('transport','运输方式')->using(Transport::$_transport);
        $grid->column('sku_cn','产品名');
        $grid->column('rate_odds','汇率');
        $grid->column('tpl_rmb','TP1(RMB)')->view('operation.profit-try.tpl-rmb');
        $grid->column('TP1')->display(function (){
            if(!$this->rate_odds){
                return '';
            }
            return numberFormat(round($this->tpl_rmb / $this->rate_odds,3));
        });
        $grid->column('head_cost','头程费');
        $grid->column('fba_fee','FBA费')->view('operation.profit-try.fba-fee');
        $grid->column('inventory_fee','库存费');
        $grid->column('other_fee','其他平台费');
        $grid->column('commission','commission')->view('operation.profit-try.commission');
        $grid->column('return','退货费')->view('operation.profit-try.return');
        $grid->column('vat','VAT费')->view('operation.profit-try.vat');
        $grid->column('cost','成本');
        $grid->column('sale_price','销售价格')->view('operation.profit-try.sale-price');
        $grid->column('profit','毛利');
        $grid->column('profit_rate','毛利率');
        $grid->tools(function (Grid\Tools $tools) {
            $tools->append(new CalculateProfitTry());
        });
        $grid->disableActions();
        $grid->exporter(new ProfitTryExporter());
        $grid->filter(function($filter){
            $filter->column(1/2, function ($filter) {
                $filter->like('sku_cn', '产品名');
                $filter->equal('transport','运输方式')->select(Transport::$_transport);
            });
            $filter->column(1/2, function ($filter) {
                $filter->equal('country_id','国家')->select(AmazonCountry::options());
                $filter->equal('seller_id','销售')->select(User::getSellerOptions());
            });
        });
        return $grid;
    }

    protected function __options($name){
        $options = json_encode([
            'emptytext'  => '<i class="fa fa-pencil"></i>',
            'mode' => 'inline',
            "showbuttons" => false,
            'name' => $name,
        ]);

        return substr($options, 0, -1).<<<'STR'
    ,
    "success":function(response, newValue){
        if (typeof response === 'object') {
            $.pjax.reload('#pjax-container');
            if (response.status){
                $.admin.toastr.success(response.message, '', {positionClass:"toast-top-center"});
            } else {
                $.admin.toastr.error(response.message, '', {positionClass:"toast-top-center"});
            }
        }
    }
}
STR;
    }

    protected function _script()
    {
        $options1 = $this->__options('commission');
        $options2 = $this->__options('fba_fee');
        $options3 = $this->__options('return');
        $options4 = $this->__options('sale_price');
        $options5 = $this->__options('tpl_rmb');
        $options6 = $this->__options('vat');

        return <<<EOT
$('.grid-editable-commission').editable($options1);
$('.grid-editable-fba_fee').editable($options2);
$('.grid-editable-return').editable($options3);
$('.grid-editable-sale_price').editable($options4);
$('.grid-editable-tpl_rmb').editable($options5);
$('.grid-editable-vat').editable($options6);
EOT;
    }

    public function update($id)
    {
        try{
            $name = Request::get('name');
            $value = trim(Request::get('value'));
            DB::beginTransaction();
            $model = ProfitTry::query()->find($id);
            $model->{$name} = $value;
            $flag = $model->save();
            if(!$flag){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败！']);
            }
            $currencyCode = AmazonCountry::query()->where('country_id',$model->country_id)->value('currency_code');
            if($currencyCode){
                $model->rate_odds = ExchangeRate::getRateOddsToRMB($currencyCode,time());
            }
            $tpl = round($model->tpl_rmb / $model->rate_odds,3);
            $model->cost = ProfitSku::getCost($tpl,$model->sale_price,$model->head_cost,$model->fba_fee,$model->commission,$model->return,$model->vat);
            $model->profit = round($model->sale_price - $model->cost,3);
            $model->profit_rate = round($model->profit / $model->sale_price,3);
            $flag1 = $model->save();
            if(!$flag1){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败！']);
            }else{
                DB::commit();
                return response()->json(['status' => true, 'message' => '操作成功！']);
            }
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统错误！']);
        }
    }

    public function create(Content $content)
    {
        return $content->header('利润率核算')
            ->description('新增')
            ->body(view('operation.profit-try.add'));
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new ProfitAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }
}
